# -*- coding: utf-8 -*-
# @Time    : 2024/11/7 下午1:56
# @Author  : xiaowanzi
# @File    : excel_operation.py
from base.project_path import get_project_path
from openpyxl import load_workbook
from configobj import ConfigObj


class ExcelOperation(object):
    def __init__(self, file):
        conf_ini = get_project_path() + "\\config.ini"
        config = ConfigObj(conf_ini, encoding='UTF8')
        hj = config['HJ']['hj']
        if file:
            file_name = config[hj][file]
        else:
            file_name = config[hj]["file"]
        self.file_path = get_project_path() + "\\excel\\%s" % file_name

    '''读取excel'''
    def read_excel(self, sheet_name):
        """
        封装 Excel 读取数据
        :param sheet_name: 数据文件中表的名称（sheet页名字）
        :return: 返回一个 字典 的二维集合
        """
        wb = load_workbook(self.file_path)
        sheet = wb[sheet_name]
        dic_data = {}
        case = {}
        for i in range(2, sheet.max_row + 1):  # 行数据，要去掉第一行标题，所以从2开始
            for j in range(1, sheet.max_column + 1):
                title = sheet.cell(row=1, column=j).value
                value = sheet.cell(row=i, column=j).value
                dic_data[title] = value  # 将数据转换字典进行存储
            # column=4，第四列的数据是测试用例函数的名称，用来区分每一个案例的数据
            case[sheet.cell(row=i, column=4).value] = dic_data.copy()
        return case

    '''写excel'''
    def write_excel(self, sheet_name, date_dict: dict):
        wb = load_workbook(self.file_path)
        sheet = wb[sheet_name]
        # 写入列名
        j = 0
        for kye in date_dict[list(date_dict.keys())[0]]:
            j += 1
            sheet.cell(row=1, column=j).value = kye
        # 写入各列值
        i = 1
        for key_i in date_dict.keys():
            i += 1
            j = 0
            for key_j in date_dict[key_i]:
                j += 1
                sheet.cell(row=i, column=j).value = date_dict[key_i][key_j]
        wb.save(self.file_path)  # 保存文件
